package cn.xxy.datasource;

import cn.xxy.beans.DataSourceConfig;
import cn.xxy.utils.ConvertUtils;

import javax.sql.DataSource;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

public abstract class DataSourceAdapter {

	protected abstract DataSource adapter(DataSourceConfig config);
	
	protected abstract DataSource adapter(Map<String, String> config);

	protected void injectProperty(Object obj, Map<String, String> config) {
		try {
			Class<? extends Object> clszz = obj.getClass();
			Method[] methods = clszz.getMethods();
			for (Method method : methods) {
				String methodName = method.getName();
				Class<?>[] paramTypes = method.getParameterTypes();
				Class<?> returnType = method.getReturnType();

				if (methodName.length() > 3 && methodName.startsWith("set")) {
					String key = methodName.substring(3);
					key = (String.valueOf(key.charAt(0)).toLowerCase()) + key.substring(1);

					if (paramTypes != null && paramTypes.length == 1 && returnType == Void.TYPE) {
						if (config.containsKey(key)) {
							Object value = ConvertUtils.convert(config.get(key).toString(), paramTypes[0]);
							method.invoke(obj, value);
						}
					}
				}
			}
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
	protected void injectProperty(Object obj, java.util.Properties config) {
		try {
			injectProperty(obj, (Map)config);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
}
